<?php

namespace app\admin\controller\business;

use app\admin\model\SystemAdmin;
use app\common\controller\AdminController;
use app\common\model\BusinessDistrict;
use app\common\model\DistrictShopCategoryModel;
use app\common\model\ShopManage;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\Exception;
use think\facade\Db;
use think\helper\Str;

/**
 * @ControllerAnnotation(title="店铺表")
 */
class Shop extends AdminController
{

    use \app\admin\traits\Curd;

    protected $allowModifyFields
        = [
            'platform_goods_switch',
            'share_goods_switch',
        ];

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\common\model\Shop();


    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        $districtId = input('district_id', 0, 'intval');
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            //var_dump($where);
            if ($districtId) {
                $where[] = ['s.district_id', '=', $districtId];
            }
//            if ($this->user['role'] == 1) {
//                $shopIds = \app\common\model\Shop::where('user_id', $this->user['id'])->column('id');
//                if ($shopIds) {
//                    $where[] = ['id', 'in', $shopIds];
//                }
//            }
            //获取商圈分类信息
            $categoryList = DistrictShopCategoryModel::where('district_id', $districtId)->field('name,shop_list')->select();
            $count        = $this->model
                ->alias('s')
                ->where($where)
                ->count();
            $list         = $this->model
                ->alias('s')
                ->where($where)
                ->leftJoin('pm_business_district bd', 's.district_id = bd.id')
                ->leftJoin('pm_user u', 's.user_id = u.id')
                ->page($page, $limit)
                ->order('s.status', 'desc')
                ->order('points_one', 'asc')
                ->field('s.*,bd.name as district_name,u.nickname')
                ->select();

            foreach ($list as &$v) {
                $v->category_id   = 0;
                $v->category_name = '';
                foreach ($categoryList as $vv) {
                    if (strpos($vv->shop_list, $v->id . '') !== false) {
                        $v->category_id   = $vv->id;
                        $v->category_name = $vv->name;
                    }
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('district_id', $districtId);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'category_id|分类id' => 'require',
                'district_id|商圈id' => 'require',
            ];
            $this->validate($post, $rule);

            $categoryList = DistrictShopCategoryModel::where('district_id', $post['district_id'])->select();

            Db::startTrans();
            try {
                foreach ($categoryList as $v) {
                    if ($post['category_id'] != $v->id) {
                        $arr = explode(',', $v->shop_list);
                        if ($arr) {
                            if (in_array($id, $arr)) {
                                foreach ($arr as $kk => $vv) {
                                    if ($id == $vv) {
                                        unset($arr[$kk]);
                                    }
                                }
                            }
                            $v->shop_list = implode(',', $arr) . '';
                            $v->save();
                        }
                    } else {
                        if ($v->shop_list) {
                            $v->shop_list = $v->shop_list . ',' . $id;
                        } else {
                            $v->shop_list = $id . '';
                        }
                        $v->save();
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('保存失败：' . $e->getMessage());
            }
            $this->success('保存成功');
        }
        $district = BusinessDistrict::where([])->field('name,id')->select()->toArray();
        $category = DistrictShopCategoryModel::where('district_id', $row->district_id)->select();
        foreach ($category as $v) {
            if (strpos($v->shop_list, $row->id . '')) {
                $row->category_id = $v->id;
            }
        }
        $this->assign('district', $district);
        $this->assign('category', $category);
        $this->assign('row', $row);
        return $this->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'phone' => 'require',
            ];
            $this->validate($post, $rule);

            $user = \app\common\model\User::where('phone', $post['phone'])->find();
            if (!$user) {
                $this->error('当前手机号用户不存在');
            }

            Db::startTrans();
            try {
                $userId          = $user->id;
                $post['user_id'] = $userId;
                if (isset($post['file'])) {
                    unset($post['file']);
                }
                if (!$post['shop_code']) {
                    $post['shop_code'] = Str::random(6, 2);
                }
                $shop = \app\common\model\Shop::create($post);
                ShopManage::create([
                    'user_id'      => $userId,
                    'shop_id'      => $shop->id,
                    'role'         => 1,
                    'function_arr' => '1,2,3,4',
                    'status'       => 1,
                    'remark'       => '后台生成店铺'
                ]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('保存失败:' . $e->getMessage());
            }
            $shop ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    public function list()
    {
        $page     = input('page', 1, 'intval');
        $pageSize = input('page_size', 15, 'intval');
        $keyword  = input('keyword', '', 'trim');
        $selected = input('selected', '', 'trim');
        $exclude  = input('exclude', '', 'trim');
        $where    = [];

        if ($keyword) {
            $where[] = ['name', 'like', "%$keyword%"];
        }
        if ($exclude) {
            $where[] = ['id', 'not in', explode(',', $exclude)];
        }
        $list       = \app\common\model\Shop::where($where)->field('name,id as value');
        $totalCount = $list->count();
        $totalPage  = ceil($totalCount / $pageSize);

        if ($selected) {
            $list = $list->orderRaw('field(id,' . $selected . ') desc');
        }
        $list = $list->order('id desc')->page($page, $pageSize)->select()->toArray();
        foreach ($list as $k => $l) {
            if (in_array($l['value'], explode(',', $selected))) {
                $list[$k]['selected'] = true;
            }
        }
        return $this->success('', ['list' => $list, 'total_page' => $totalPage]);
    }
}